<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px"> <!-- 标签宽度加大 -->
      <el-form-item label="兑换码" prop="redeemCode">
        <el-input v-model="queryParams.redeemCode" placeholder="请输入兑换码" clearable />
      </el-form-item>
      <!-- 搜索条件里的关联优惠券 -> 下拉 -->
      <el-form-item label="关联优惠券" prop="couponId">
        <el-select
            v-model="queryParams.couponId"
            placeholder="请选择关联优惠券"
            filterable
            clearable
            style="width: 180px">
          <el-option
              v-for="item in couponOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 20px"> <!-- 间距加大 -->
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="couponRedeemCodeList" @selection-change="handleSelectionChange" style="width: 100%;">
      <!-- 选择框 -->
      <el-table-column type="selection" width="55" align="center" />

      <!-- 固定较小宽度 -->
      <el-table-column label="ID" prop="id" align="center" width="50" />
      <!-- 自适应填充的列（不要设宽度） -->
      <el-table-column label="兑换码" prop="redeemCode" align="center" width="140" />
      <el-table-column label="关联优惠券名称" prop="couponInfo.name" align="center" width="150"/>
      <el-table-column label="优惠券类型" align="center" width="150">
        <template #default="scope">
          <dict-tag :options="coupon_type" :value="scope.row.couponInfo?.couponType" />
        </template>
      </el-table-column>
      <el-table-column label="总数" prop="totalCount" align="center" width="60" />
      <el-table-column label="可用数量" prop="availableQuantity" align="center" width="80" />
      <!-- 稳定宽度列 -->
      <el-table-column label="兑换时间范围" align="center" width="240">
        <template #default="scope">
          <div style="display: flex; justify-content: center; align-items: center; gap: 8px;">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
            <span>至</span>
            <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="createTime" align="center" width="220">
        <template #default="scope">
          <span style="white-space: nowrap;">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <div style="white-space: nowrap;">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['transaction:CouponRedeemCode:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['transaction:CouponRedeemCode:remove']">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 弹窗 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="兑换码" prop="redeemCode">
          <el-input v-model="form.redeemCode" placeholder="请输入兑换码" />
        </el-form-item>
        <el-form-item label="关联优惠券" prop="couponId">
          <el-select
              v-model="form.couponId"
              placeholder="请选择关联优惠券"
              filterable
              clearable
              style="width: 100%">
            <el-option
                v-for="item in couponOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="总数" prop="totalCount">
          <el-input-number v-model="form.totalCount" :min="1" />
        </el-form-item>
        <el-form-item label="可用数量" prop="availableQuantity">
          <el-input-number v-model="form.availableQuantity" :min="0" />
        </el-form-item>
        <el-form-item label="有效期" prop="timeRange">
          <el-date-picker
              v-model="form.timeRange"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              range-separator="至"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { listCouponRedeemCode, getCouponRedeemCode, addCouponRedeemCode, updateCouponRedeemCode, delCouponRedeemCode,getCouponRedeemCodeByCode } from "@/api/transaction/couponRedeemCode"
import { listCouponInfo } from "@/api/transaction/couponInfo"
import { ref } from "vue"
const { proxy } = getCurrentInstance()
const { coupon_type } = proxy.useDict('coupon_type')
const loading = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const couponRedeemCodeList = ref([])
const title = ref("")
const open = ref(false)
const couponOptions = ref([])

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  redeemCode: null,
  couponId: null
})

const form = ref({})
const rules = {
  redeemCode: [{ required: true, message: "兑换码不能为空", trigger: "blur" }],
  couponId: [{ required: true, message: "请选择关联优惠券", trigger: "change" }]
}

// 加载优惠券下拉选项：关联优惠券表，显示优惠券的全部名称，选中优惠券名称时记录相关的优惠券ID
function loadCouponOptions() {
  return listCouponInfo({ pageNum: 1, pageSize: 1000 }).then(res => {
    const rows = res.rows || (res.data && res.data.rows) || res.data || []
    couponOptions.value = Array.isArray(rows) ? rows.map(r => ({ id: r.id, name: r.name })) : []
  }).catch(() => {
    couponOptions.value = []
  })
}

// 列表
function getList() {
  loading.value = true
  listCouponRedeemCode(queryParams.value).then(res => {
    couponRedeemCodeList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

// 新增
function handleAdd() {
  reset()
  loadCouponOptions().then(() => {
    open.value = true
    title.value = "添加优惠券兑换码"
  })
}

// 修改
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCouponRedeemCode(_id).then(response => {
    form.value = {
      ...response.data,
      timeRange: response.data.startTime && response.data.expireTime
          ? [response.data.startTime, response.data.expireTime]
          : null
    }
    loadCouponOptions().then(() => {
      open.value = true
      title.value = "修改优惠券兑换码"
    })
  })
}

// 删除
function handleDelete(row) {
  const _ids = row.id || ids.value
  delCouponRedeemCode(_ids).then(() => {
    getList()
  })
}

// 选择框变化
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  queryParams.value = { pageNum: 1, pageSize: 10, redeemCode: null, couponId: null }
  getList()
}

function reset() {
  form.value = {
    id: null,
    redeemCode: null,
    couponId: null,
    totalCount: null,
    availableQuantity: null,
    timeRange: null
  }
}

function submitForm() {
  const payload = {
    ...form.value,
    startTime: form.value.timeRange ? form.value.timeRange[0] : null,
    expireTime: form.value.timeRange ? form.value.timeRange[1] : null
  }
  if (payload.id) {
    updateCouponRedeemCode(payload).then(() => {
      open.value = false
      getList()
    })
  } else {
    addCouponRedeemCode(payload).then(() => {
      open.value = false
      getList()
    })
  }
}

// 初始化
loadCouponOptions().then(() => {
  getList()
})
</script>
